﻿using iTextSharp.text;
using iTextSharp.text.pdf;
using iTextSharp.text.pdf.codec;

namespace iPdf
{
    class TiffToPdfConverter
    {
        public static bool IsTiffFile(string fileName)
        {
            return FileFormat.TiffImage.IsOneOf(fileName);
        }

        public static void ImageToPdfPage(Document doc, PdfWriter writer, string imageFileName)
        {
            RandomAccessFileOrArray ra = new RandomAccessFileOrArray(imageFileName);
            try
            {
                int numOfPages = TiffImage.GetNumberOfPages(ra);

                PdfContentByte cb = writer.DirectContent;
                
                for (int i = 0; i < numOfPages; ++i)
                {
                    iTextSharp.text.Image img = TiffImage.GetTiffImage(ra, i+1);
                    img.SetAbsolutePosition(0, 0);
                    doc.SetPageSize(new iTextSharp.text.Rectangle(img.Width, img.Height));
                    doc.NewPage();
                    cb.AddImage(img);
                }
            }
            catch
            {
                ra.Close();
                throw;
            }
        }
    }
}
